/**
 * 配置条件区域
 * @param condition
 */
function conditionConf(condition){
	var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
	conditionPanel.add({
		xtype: 'container',
	    margin: '0 0 0 0',
	    columnWidth: .99,
	    layout: 'column',
	    defaults: {
	    	margin: '4 4 4 10',
	        columnWidth: .13,
	        labelAlign:'right',
	        labelWidth: 90//控件默认标签宽度
	    },
	    items: [{
	    	xtype: 'button',
	        name: 'sort',
	        text:'<span class="button-font">条件排序</span>',
	        baseCls:'x-panel-button-new',
	        icon: '/report/image/sysbutton/sort.png',
	        tooltip:'条件排序',
	        handler: function (btn,e) {
	        	Ext.create('Ext.window.Window', {
	        		title: '条件排序', // 窗口标题
	                width: document.body.clientWidth * 0.3, // 窗口宽度
	                height: document.body.clientHeight * 0.7, // 窗口高度
	                layout: 'fit',
	                maximizable: true,
	                itemId: 'window_sort_info', // 窗口标识
	                buttonAlign: 'right', // 按钮显示的位置
	                modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
	                closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
	                items: initWindow_sort_info(),
	                buttons: [{
	                	xtype: 'button',
	              		text: '确定',
	              		handler: function (self) {
	              			var grid = DSYGrid.getGrid('sortGrid');
	              			var store = grid.getStore();
	              			var sortcondition = [];
	              			store.each(function(record){
	              				sortcondition.push(record.getData());
	              			});
	              			conditionList = {};
	              			conditionList = sortcondition;
	              			self.up('window').close();
	              			var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
	              			conditionPanel.removeAll(true);
	              			conditionConf(conditionList);
	              		}
	                },{
	                	xtype: 'button',
	                    text: '关闭',
	                    handler: function (self) {
	                    	self.up('window').close();
	                    }
	                }]
	             }).show();
	        }
	    }]
	}); 
	if(condition != null&&condition.length>0){
		Ext.Array.forEach(condition,function(str){ //单纯的遍历数组 
			var code = str.C_CODE;
	    	var fieldtitle = str.C_TITLE;
	    	var tips = str.C_TIPS;
		    var cid = str.C_ID;
		    var isShow = str.IS_SHOW;
		    var fieldLabel = '<span ondblclick="deleteCondition(\''+code+'\',\'combobox\',\''+cid+'\');">'+fieldtitle+'</span>';
		    if(isShow == 0){
		    	fieldLabel = '<span class="no-show" ondblclick="deleteCondition(\''+code+'\',\'combobox\',\''+cid+'\');">'
		    				  +fieldtitle+'</span>';
		    }
		    conditionPanel.add({
		    	xtype: 'combobox',
	    		fieldLabel: fieldLabel,
	    		name: code,
	    		margin:'2 5 2 2',
	    		padding:'0 0 0 0',
	            emptyText: tips,
	            listeners: {
	            	render:function(self){
	            		Ext.QuickTips.init();  
	            		Ext.QuickTips.register({  
                  	    	target : self.el,  
                  	        text : '双击标题删除'
                  	    });
	            		self.getEl().on('click', function(self){
	                  		if(timer1){
	                      		timer1 = false;
	                      		task1 = new Ext.util.DelayedTask(function(){
	                      			var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
	              	        		rightConfig.removeAll(true);
	              	        		rightConfig.setTitle("查询条件配置");
	              	        		var data = [];
	              	        		var dataFlag = false;
	              	        		for(var i = 0; i < conditionList.length; i++){
	              	        			var conditionCid = conditionList[i].C_ID;
	              	        			if(cid == conditionCid){
	              	        				data = conditionList[i];
	              	        				dataFlag = true;
	              	        				break;
	              	        			}
	              	        		}
	              	        		if(dataFlag){
	              	        			rightConfig.add(initConditonConfig({
	          	                        	c_id:cid,
	          	                            data: data
	          	                        }));
	              	        		}
	                         		timer1 = true;
	                          	});
	                      		task1.delay(300);
	                  		}
	            		}); 
	            	}
	            }	    	    		
	    	});
		}); 
	}
}


/**
 * 条件排序配置界面
 * @returns
 */
function initWindow_sort_info(){
	var tbar = [{
		xtype: 'button',
		text: '置顶',
		handler: function (btn) {
            var grid = DSYGrid.getGrid('sortGrid');
            var store = grid.getStore();
            var record = grid.getSelectionModel().getSelection()[0];
            var index = store.indexOf(record);
            if (index > 0) {  
            	store.removeAt(index);  
            	store.insertData(0, record);  
            	//grid.getView().select(record);
            	//grid.getView().refresh();
            	grid.getView().addRowCls(record,"x-grid-item-click-new");
            	grid.getSelectionModel().selectRange(0, 0);
            } 
		}
	},{
		xtype: 'button',
	    text: '置底',
	    handler: function (btn) {
	    	var grid = DSYGrid.getGrid('sortGrid');
	        var store = grid.getStore();
	        var record = grid.getSelectionModel().getSelection()[0];
	        var index = store.indexOf(record);
	        if (index >= 0) {  
	        	store.removeAt(index);  
	            store.insertData(store.getCount(), record);  
	            grid.getSelectionModel().selectRange(store.getCount() - 1, store.getCount() - 1);
	            //grid.getView().select(record);
	            grid.getView().refresh();
	            grid.getView().addRowCls(record,"x-grid-item-click-new");
	        } 
	    }
	},{
		xtype: 'button',
	    text: '上移',
	    handler: function (btn) {
	    	var grid = DSYGrid.getGrid('sortGrid');
	        var store = grid.getStore();
	        var record = grid.getSelectionModel().getSelection()[0];
	        var index = store.indexOf(record);
	        if (index > 0) {  
	        	store.removeAt(index);  
	            store.insertData(index - 1, record);  
	            grid.getSelectionModel().selectRange(index - 1, index - 1);
	            //grid.getView().select(record);
	            grid.getView().refresh();
	            grid.getView().addRowCls(record,"x-grid-item-click-new");
	        } 
	    }
	},{
		xtype: 'button',
  	    text: '下移',
  	    disabled: false,
  	    handler: function (btn) {
  	    	var grid = DSYGrid.getGrid('sortGrid');
  	        var store = grid.getStore();
  	        var record = grid.getSelectionModel().getSelection()[0];
  	        var index = store.indexOf(record);
  	        if (index < store.getCount() - 1 && index >= 0) {  
  	        	store.removeAt(index);  
  	            store.insertData(index + 1, record);  
  	            grid.getSelectionModel().selectRange(index + 1, index + 1);
  	            //grid.getView().select(record);
  	            grid.getView().refresh();//刷新行号  
  	            grid.getView().addRowCls(record,"x-grid-item-click-new");
  	        }
  	    }
	}];
	var headerJson = [{
		dataIndex: "C_CODE",
        type: "string",
        text: "控件编码",
        width: 150
	},{
        dataIndex: "C_TITLE",
        type: "string",
        text: "控件名称",
        width: 150
    }];
	var grid = DSYGrid.createGrid({
		itemId: 'sortGrid',
        headerConfig: {
        	headerJson: headerJson,
            columnAutoWidth: false
        },
        checkBox: false,
        border: false,
        autoLoad: false,
        dockedItems: [{
        	xtype: 'toolbar',
            dock: 'right',
            items: tbar
        }],
        height: '100%',
        flex: 1,
        data:conditionList,
        pageConfig: {
        	enablePage: false
        }
	});
	return grid;
}

/**
 * 删除条件
 * @param name
 * @param controlType
 * @param cid
 */
function deleteCondition(name,controlType,cid){
	changeFlag = true;
	if(task1){
		task1.cancel();
		timer1 = true;
	}
	var assembly = Ext.ComponentQuery.query(''+controlType+'[name="' +name + '"]')[0];
	assembly.destroy();
	var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
	rightConfig.removeAll(true);
	Ext.Array.forEach(conditionList, function (str, index, conditionList) { //单纯的遍历数组
        if(str){
        	if (str.C_ID == cid) {
        		conditionList.splice(index, 1);
            }
        }
    });
}



/**
 * 条件配置
 * @param config
 * @returns
 */
function initConditonConfig(config){
    var form = Ext.create('Ext.form.Panel', {
        width: '100%',
        height: '100%',
        itemId: 'window_tjpz_contentForm',
        layout: 'column',
        defaultType: 'textfield',
        scrollable:true,
        defaults: {
            margin: '5 5 2 5',
            columnWidth: .99,
            labelAlign: "right",
            labelWidth: 110//控件默认标签宽度
        },
        items: [{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>控件编码',
			name: 'C_CODE',
			displayField: 'name',
            valueField: 'id',
            store: conditionCodeStore(q_id),
            editable: true,
			allowBlank: false,
			enableKeyEvents:true,
			listeners: { 
				expand:function(self , eOpts ){
					self.getStore().load();
				},
	            select:function ( combo, record, eOpts ) {
	            	if(config.saveFlag){
	            		conditionConfig(config.c_id);
	            	}
	            },
				keyup:function ( self, e, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	fieldLabel: '<span class="required">✶</span>控件名称',
			name: 'C_TITLE',
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					var c_code = null;
				    var SHOW_CODE = null;
				    var isShow = 1;
				    for(var key in conditionList){
				    	if(config.c_id == conditionList[key].C_ID){
				    	c_code = conditionList[key].C_CODE;
				    	SHOW_CODE = conditionList[key].SHOW_CODE;
				    	isShow = conditionList[key].IS_SHOW;
				    	}
				    }
				    var name = c_code;
				    var fieldLabel = '<span ondblclick="deleteCondition(\''+name+'\',\'combobox\',\''
				    				  +config.c_id+'\');">'+newValue+'</span>';
				    if(isShow == 0){
				    	fieldLabel = '<span class="no-show" ondblclick="deleteCondition(\''
				    				  +name+'\',\'combobox\',\''+config.c_id+'\');">'+newValue+'</span>';
				    }
				    var assembly = Ext.ComponentQuery.query('combobox[name="' +name + '"]')[0];
				    if(assembly){
				    	assembly.setFieldLabel(fieldLabel);
				    }else{
				    	name = SHOW_CODE;
				    	assembly = Ext.ComponentQuery.query('combobox[name="' +name + '"]')[0];
				    	if(assembly){
				    		assembly.setFieldLabel(fieldLabel);
				    	}
				    }
				    if(config.saveFlag){
				    	saveConditionFormValues(config.c_id);
				    }
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '查询列',
			name: 'C_FIELD_CODE',
			displayField: 'text',
            valueField: 'id',
            store: Ext.ComponentQuery.query('treepanel#fieldTree')[0].getStore(),
            editable: false,
			allowBlank: true,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>控件类型',
			name: 'C_DISP_MODE',
			displayField: 'name',
            valueField: 'id',
            value: 'textfield',
            store: DebtEleStore(json_disp_mode_type),
            editable: false,
			allowBlank: false,
			listeners:{  
				select:function(combo, record,index){
					dispModeControl();
				},
                change : function( self, newValue, oldValue, eOpts ){
                	if(config.saveFlag){
                		saveConditionFormValues(config.c_id);
                	}
                }
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>是否多选',
			name: 'IS_MUL',
			displayField: 'name',
            valueField: 'id',
            value: 0,
            store: DebtEleStore(json_mul),
            editable: false,
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>只返回叶子节点',
			name: 'IS_LEAF',
			displayField: 'name',
            valueField: 'id',
            value: 0,
            store: DebtEleStore(json_leaf),
            editable: false,
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>允许为空',
			name: 'IS_MUST_INPUT',
			displayField: 'name',
            valueField: 'id',
            value: 0,
            store: DebtEleStore(json_must_type),
            editable: false,
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>权限过滤',
			name: 'IS_RIGHT',
			displayField: 'name',
			valueField: 'id',
            value: 0,
            store: DebtEleStore(json_right),
            editable: false,
			allowBlank: false,//允许为空
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	fieldLabel: '枚举项',
			name: 'C_DATA_MODEL',
			allowBlank: true,
			emptyText:'key#value+key1#value1',
			validator:function(val) {
				if (!Ext.isEmpty(val)) {
					var keyValues = val.split("+");
					for (var i = 0; i < keyValues.length; i++){
						var keyValue = keyValues[i];
					    var key_value = keyValue.split("#");
					    if(key_value.length != 2 || key_value[1] == undefined||key_value[1] == null ||key_value[1] == ""){
					    	return "格式不正确,请输入正确的值:key#value+key1#value1";
						}
					} 
				}
				return true;
			},
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	xtype:'textareafield',
			fieldLabel: '数据集<image onmouseover="sqlTip()" src="/report/image/common/alarmTip.png" width="12px"  height="12px">',
			name: 'C_DATA_SOURCE',
			allowBlank: true,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	xtype: 'button',
            text: '数据集',
            columnWidth: 0.35,
            icon: '/report/image/sysbutton/search.png',
            handler: function (self) {
            	sqlSelect()
            }
        },{
        	xtype: 'button',
        	text: '编辑',
        	columnWidth: 0.3,
            icon: '/report/image/sysbutton/edit.png',
            handler: function (self) {
            	var dataSourceSql = Ext.ComponentQuery.query('textareafield[name="C_DATA_SOURCE"]')[0].getValue();
                Ext.create('Ext.window.Window', {
                	title: '数据集修改', // 窗口标题
                  	width: document.body.clientWidth * 0.7, // 窗口宽度
                  	height: document.body.clientHeight * 0.7, // 窗口高度
                  	layout: 'fit',
                  	maximizable: true,
                  	itemId: 'window_edit_table_sql', // 窗口标识
                  	buttonAlign: 'right', // 按钮显示的位置
                  	modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                  	closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                  	items: [{
                  		xtype: 'form',
            			width: '100%',
            			height: '100%',
            			layout: 'column',
            			autoScroll: true,
            			defaults: {
            				margin: '10 5 5 5',
            			    columnWidth: .99,
            			    labelAlign: "right",
            			    labelWidth: 100//控件默认标签宽度
            			},
            			items: [{
            				xtype:'textareafield',
            			    height:'95%',
            			    name: 'EDIT_SQL',
            			    allowBlank: false,
            			    value:dataSourceSql
            			}]
                  	}],
                  	buttons: [{
                  		xtype: 'button',
                		text: '确定',
                		handler: function (self) {
                			var editSql = Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[0].getValue();
                            Ext.ComponentQuery.query('textareafield[name="C_DATA_SOURCE"]')[0].setValue(editSql);
                	        self.up('window').close();
                		}
                	},{
                		xtype: 'button',
                		text: '关闭',
                		handler: function (self) {
                			self.up('window').close();
                		}
                	}]
                }).show();
            }
        },{
        	xtype: 'button',
            text: '预览',
            columnWidth: 0.3,
            icon: '/report/image/sysbutton/search.png',
            handler: function (self) {
            	var	table = Ext.ComponentQuery.query('textareafield[name="C_DATA_SOURCE"]')[0].getValue();
                var title = Ext.ComponentQuery.query('textfield[name="C_TITLE"]')[0].getValue();
                if(table == null || table ==""){
                	Ext.MessageBox.alert('提示', '数据集为空不可预览!');
                	return;
                }
                if(table.toUpperCase().indexOf("SELECT") == -1){
                	table = "select * from " + table;
                }
                table = encode64(table);
                $.post('/report/page/plat/sys/dataCheckExecute.action', {
                	RUNSQL:table
                }, function (data) {
                	if (data.success&&data.select) {
                		var parameter = data.condition;
                        if(parameter.length > 0){
                        	Ext.create('Ext.window.Window', {
                        		title:'参数',
                              	width: document.body.clientWidth * 0.3, // 窗口宽度
                              	height: document.body.clientHeight * 0.5, // 窗口高度
                              	layout: 'fit',
                              	maximizable: true,
                              	itemId: 'window_table_condition_info', // 窗口标识
                              	buttonAlign: 'right', // 按钮显示的位置
                              	modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                              	closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                              	items: initWindow_table_condition_info(parameter),
                              	buttons: [{
                              		xtype: 'button',
	                                text: '确定',
	                                handler: function (self) {
	                                	var form = self.up('window').down('form');
	                                    var formData = form.getValues();
	                                    self.up('window').close();
	                                    $.post('/report/page/plat/sys/getTableDataHeader.action', {
	                                    	runsql:table
	                                    }, function (data) {
	                                    	if(data.header){
	                                            //弹出弹出框
	                                    		Ext.create('Ext.window.Window', {
	                                    			title: title, // 窗口标题
	                                                width: document.body.clientWidth * 0.8, // 窗口宽度
	                                                height: document.body.clientHeight * 0.8, // 窗口高度
	                                                layout: 'fit',
	                                                maximizable: true,
	                                                itemId: 'window_table_info', // 窗口标识
	                                                buttonAlign: 'right', // 按钮显示的位置
	                                                modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
	                                                closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
	                                                items: initWindow_table_info(table,data.header,title,formData),
	                                                buttons: [{
	                                                	xtype: 'button',
	                                                    text: '关闭',
	                                                    handler: function (self) {
	                                                    	self.up('window').close();
	                                                    }
	                                                }]
	                                    		}).show();
	                                    	}	
	                                    },'JSON');
	                                }
                              	},{
                              		xtype: 'button',
	                              	text: '取消',
	                              	handler: function (self) {
	                              		self.up('window').close();
	                              	}
	                           }]
                        	}).show();
                        }else{
                        	$.post('/report/page/plat/sys/getTableDataHeader.action', {
                        		runsql:table
                            }, function (data) {
                            	if(data.header){
                                    //弹出弹出框
                            		Ext.create('Ext.window.Window', {
                            			title: title, // 窗口标题
                                     	width: document.body.clientWidth * 0.8, // 窗口宽度
                                     	height: document.body.clientHeight * 0.8, // 窗口高度
                                     	layout: 'fit',
                                     	maximizable: true,
                                     	itemId: 'window_table_info', // 窗口标识
                                     	buttonAlign: 'right', // 按钮显示的位置
                                     	modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
                                     	closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
                                     	items: initWindow_table_info(table,data.header,title),
                                     	buttons: [{
                                     		xtype: 'button',
                                     	    text: '关闭',
                                     	    handler: function (self) {
                                     	    	self.up('window').close();
                                     	    }
                                     	}]
                            		}).show();
                            	}	
                            },'JSON');
                        }
                	} else if(data.success){
                		Ext.MessageBox.alert('提示', '执行sql成功!');
                    }else{
                    	Ext.MessageBox.alert('提示', data.message);
                    }
                }, 'JSON');
            }
        },{
        	fieldLabel: '控件默认值<image onmouseover="valueTip()" src="/report/image/common/alarmTip.png" width="12px" height="12px">',
			name: 'C_DATA_VALUE',
			allowBlank: true,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>查询关系符',
			name: 'QUERY_RELATION',
			displayField: 'name',
            valueField: 'id',
            value: 'like',
            store: DebtEleStore(json_query_relation),
            editable: false,
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
					}
				}
			}
        },{
        	fieldLabel: '控件tips提示',
			name: 'C_TIPS',
			allowBlank: true,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '依赖查询控件编码',
			name: 'C_SRC_ID',
			displayField: 'name',
            valueField: 'id',
            store: getSrcStore(config.c_id),
            editable: false,
			allowBlank: true,
			listeners: { 
				expand : function(self , eOpts ){
					self.getStore().load();
	            },
				change : function( self, newValue, oldValue, eOpts ){
					if(config.saveFlag){
						saveConditionFormValues(config.c_id);
                    }
				}
			}
        },{
        	xtype: 'combobox',
			fieldLabel: '<span class="required">✶</span>控件是否可见',
			name: 'IS_SHOW',
			displayField: 'name',
            valueField: 'id',
            value: 1,
            store: DebtEleStore(json_show_type),
            editable: false,
			allowBlank: false,
			listeners: { 
				change : function( self, newValue, oldValue, eOpts ){
					var c_code = null;
					var SHOW_CODE = null;
				    var title = null; 
				    for(var key in conditionList){
				    	if(config.c_id == conditionList[key].C_ID){
				    		c_code = conditionList[key].C_CODE;
				    		SHOW_CODE = conditionList[key].SHOW_CODE;
				    		title = conditionList[key].C_TITLE;
				    	}
				    }
				    var name = c_code;
				    var fieldLabel = '<span ondblclick="deleteCondition(\''+name+'\',\'combobox\',\''
				    				 +config.c_id+'\');">'+title+'</span>';
				    if(newValue == 0){
				    	fieldLabel = '<span class="no-show" ondblclick="deleteCondition(\''
				    				  +name+'\',\'combobox\',\''+config.c_id+'\');">'+title+'</span>';
					}
				    var assembly = Ext.ComponentQuery.query('combobox[name="' +name + '"]')[0];
				    if(assembly){
				    	assembly.setFieldLabel(fieldLabel);
				    }else{
				    	name = SHOW_CODE;
				    	assembly = Ext.ComponentQuery.query('combobox[name="' +name + '"]')[0];
				    	assembly.setFieldLabel(fieldLabel);
				    }
				    if(config.saveFlag){
                    	saveConditionFormValues(config.c_id);
                    }
				}
			}
        }]
    });
    //初始化及回显
    form.getForm().setValues(config.data);
    dispModeControl();
	setTimeout(function () {  
   		config.saveFlag=true;
   	}, 1000);  
    return form;
}

/**
 * 根据q_id获取条件下拉值
 * @param q_id
 * @returns
 */
function conditionCodeStore(q_id){
	var store = new Ext.data.Store({
        autoLoad: true,
        fields: ['id','code', 'name'],
        proxy: {
            type: 'ajax',
            url: '/sys-report/getContidionCodeStore',
            extraParams: {
            	Q_ID:q_id
            },
            reader: {
                type: 'json',
                root: 'list'
            }
        }
    });
	return store;
}

/**
 * 依赖查询控件下拉值
 * @param cid
 * @returns
 */
function getSrcStore(cid){
	//code#value+code1#value1
	 var json_store = new Array();
	 for(var i = 0; i< conditionList.length;i++){
		 var condition = conditionList[i];
		 if(condition.C_ID != cid){
			 var id = condition.C_ID;
			 var code = condition.C_FIELD_CODE;
			 var name = condition.C_TITLE;
			 json_store.push({id: code, code: code, name: code+" "+name});
		 }
	 }
	var store = Ext.create('Ext.data.Store', {
		fields: ['id','code', 'name'],
	    data :json_store
	});
	return store;
};

function dispModeControl(){
	var modeValue =  Ext.ComponentQuery.query('combobox[name="C_DISP_MODE"]')[0].getValue();
    var queryRelation = Ext.ComponentQuery.query('combobox[name="QUERY_RELATION"]')[0];
    var isMul = Ext.ComponentQuery.query('combobox[name="IS_MUL"]')[0];
    var isLeaf = Ext.ComponentQuery.query('combobox[name="IS_LEAF"]')[0];
    if(modeValue == "treecombobox"){
    	isMul.setHidden(false);
    	isLeaf.setHidden(false);
    }else{
    	isMul.setValue("0");
    	isMul.setHidden(true);
    	isLeaf.setValue("0");
    	isLeaf.setHidden(true);
    }
    if(modeValue == "label"){
        queryRelation.setValue("");
        queryRelation.setDisabled(true);
    }else{
    	queryRelation.setDisabled(false);
    }
}

/**
 * 下拉树sql提示
 */
function sqlTip(){
	Ext.toast({
        html: "下拉树sql需要包含以下字段：</br><table>" +
    	"<tr><td>GUID</td><td>数据唯一ID</td></tr>" +
    	"<tr><td>CODE</td><td>编码</td></tr>" +
    	"<tr><td>NAME</td><td>名称</td></tr>" +
    	"<tr><td>SUPERGUID</td><td>父节点GUID</td></tr>" +
    	"<tr><td>ISLEAF</td><td>是否子节点</td></tr>" +
    	"<tr><td>LEVELNO</td><td>级次</td></tr></table>" +
    	"示例：SELECT GUID,CODE,NAME,SUPERGUID ,ISLEAF, LEVELNO FROM DSY_V_ELE_AD </br>"+
    	"下拉框sql需要包含以下字段：</br><table>" +
    	"<tr><td>GUID</td><td>数据唯一ID</td></tr>" +
    	"<tr><td>CODE</td><td>编码</td></tr>" +
    	"<tr><td>NAME</td><td>名称</td></tr></table>" +
    	"示例：SELECT GUID,CODE,NAME FROM DSY_V_ELE_AD </br>",
        closable: false,
        align: 't',
        padding:'1px',
        bodyStyle: 'padding:1px',
        border:false,
        slideInDuration: 400,
        minWidth: 400
    });
}

/**
 * 默认值提示
 */
function valueTip(){
	Ext.toast({ 
        html: "默认值必须为SQL且必须包含C_DATA_VALUE字段</br>" +
    	"示例：SELECT C_SDATE C_DATA_VALUE FROM DSY_V_QUERYDEFAULT </br>",
        closable: false,
        align: 't',
        padding:'1px',
        bodyStyle: 'padding:1px',
        border:false,
        slideInDuration: 400,
        minWidth: 400
    });
}


/**
 * 获取系统数据集
 * @returns
 */
function sqlSelect(){
    //弹出弹出框
   Ext.create('Ext.window.Window', {
       title: '条件数据集', // 窗口标题
       width: document.body.clientWidth * 0.6, // 窗口宽度
       height: document.body.clientHeight * 0.6, // 窗口高度
       layout: 'fit',
       maximizable: true,
       buttonAlign: 'right', // 按钮显示的位置
       modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
       closeAction: 'destroy',//hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
       items: initWindow_sqlSelect_content(),
       buttons: [{
    	   xtype: 'button',
    	   text: '确定',
    	   handler: function (self) {
    		   var record = DSYGrid.getGrid('sqlSelectGrid').getCurrentRecord();
    		   if (record==null) {
    			   self.up('window').close();
    			   return;
    		   }
    		   var C_DATA_SOURCE = record.get("C_DATA_SOURCE");
    		   Ext.ComponentQuery.query('textareafield[name="C_DATA_SOURCE"]')[0].setValue(C_DATA_SOURCE);
    		   self.up('window').close();
    	   }
       },{
    	   xtype: 'button',
    	   text: '关闭',
    	   handler: function (self) {
    		   self.up('window').close();
    	   }
       }]
   }).show();
}

/**
 * 系统数据集列表
 * @returns
 */
function initWindow_sqlSelect_content(){
	var headerJson = [{
		dataIndex: "C_CODE",
		type: "string",
		text: "控件编码",
		width: 150
	},{
		dataIndex: "C_TITLE",
		type: "string",
		text: "控件名称",
		width: 150
	},{
		dataIndex: "C_DATA_SOURCE",
		type: "string",
		text: "数据集",
		width: 400,
		cellWrap:true
	}];
    var grid = DSYGrid.createGrid({
        itemId: 'sqlSelectGrid',
        headerConfig: {
            headerJson: headerJson,
            columnAutoWidth: false
        },
        checkBox: false,
        border: false,
        autoLoad: true,
        height: '100%',
        dataUrl:'/sys-report/getConditionSelectSql',
        pageConfig: {
            enablePage: false
        }
    });
    return grid;
}


/**
 * 系统条件模板
 * @param c_id
 * @returns
 */
function conditionConfig(c_id){
	var form=Ext.ComponentQuery.query('form#window_tjpz_contentForm')[0];
	var conditionCode = Ext.ComponentQuery.query('combobox[name="C_CODE"]')[0].getValue();
	Ext.Ajax.request({
		method : 'POST',
		url : "/sys-report/getConditionConfigByCode",
		params : {
			conditionCode: conditionCode
		},
		async : false,
		success : function(response, options) {
			// 获取返回的JSON，并根据gridid，获取表头配置信息
			var respText = Ext.util.JSON.decode(response.responseText);
			if(respText.success){
				var conditionConfig =  eval(respText.conditionList)[0];
				form.getForm().setValues(conditionConfig);
			}
		},
		failure : function(response, options) {
			
		}
	});
	saveConditionFormValues(c_id);
}

/**
 * 条件写值
 * @param c_id
 * @returns
 */
function saveConditionFormValues(c_id){
	changeFlag = true;
	var form=Ext.ComponentQuery.query('form#window_tjpz_contentForm')[0];
	var formValues = form.getForm().getValues();
	for(var i=0;i<conditionList.length;i++){
 		if(conditionList[i]&&conditionList[i].C_ID == c_id){
 			conditionList[i].C_CODE = formValues.C_CODE;
 			conditionList[i].C_DATA_MODEL = formValues.C_DATA_MODEL;
 			conditionList[i].C_DATA_SOURCE = formValues.C_DATA_SOURCE;
 			conditionList[i].C_DATA_VALUE = formValues.C_DATA_VALUE;
 			conditionList[i].C_DISP_MODE = formValues.C_DISP_MODE;
 			conditionList[i].C_FIELD_CODE = formValues.C_FIELD_CODE;
 			conditionList[i].C_SRC_ID = formValues.C_SRC_ID;
 			conditionList[i].C_TIPS = formValues.C_TIPS;
 			conditionList[i].C_TITLE = formValues.C_TITLE;
 			conditionList[i].IS_LEAF = formValues.IS_LEAF;
 			conditionList[i].IS_MUL = formValues.IS_MUL;
 			conditionList[i].IS_MUST_INPUT = formValues.IS_MUST_INPUT;
 			conditionList[i].IS_RIGHT = formValues.IS_RIGHT;
 			conditionList[i].IS_SHOW = formValues.IS_SHOW;
 			conditionList[i].QUERY_RELATION = formValues.QUERY_RELATION;
 			break;
 		}
 	}
}

var fieldRightClick = new Ext.menu.Menu({
    float: true,
    items: [ {
        text: '添加为条件',
        //增加菜单点击事件
        handler: function () {
        	var code = currentNode.get('code');
        	var fieldtitle = currentNode.get('title');
        	var flag = true;
        	var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
        	conditionPanel.items.each(function (item, index, length) {
                var label = item.name;
                if (code == label) {
                      alert("条件已存在");
                      flag = false;
                      return;
                  }
            });
        	if(flag){
        		var cid = GUID.createGUID();
        		conditionList.push({
        			C_ID:cid,
        			C_CODE:code,
            		SHOW_CODE:code,
            		C_TITLE: fieldtitle
        		});
        		conditionPanel.add({
     	    		xtype: 'combobox',
     	    		fieldLabel: '<span ondblclick="deleteCondition(\''+code+'\',\'combobox\',\''+cid+'\');">'+fieldtitle+'</span>',
     	    		name: code,
                    margin:'2 5 2 2',
                    padding:'0 0 0 0',
                    listeners: {
                         render:function(self){
                         	Ext.QuickTips.init();  
                         	Ext.QuickTips.register({  
                         		target : self.el,  
                         	    text : '双击标题删除'
                         	});
                         	self.getEl().on('click', function(self){ 
                        		if(timer1){
                            		timer1 = false;
                            		task1 = new Ext.util.DelayedTask(function(){
                            			var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
                      	        		rightConfig.removeAll(true);
                      	        		rightConfig.setTitle("查询条件配置");
                      	        		var data = [];
                      	        		var dataFlag = false;
                      	        		for(var i = 0; i < conditionList.length; i++){
                      	        			var conditionCid = conditionList[i].C_ID;
                      	        			if(cid == conditionCid){
                      	        				data = conditionList[i];
                      	        				dataFlag = true;
                      	        				break;
                      	        			}
                      	        		}
                      	        		if(dataFlag){
                      	        			rightConfig.add(initConditonConfig({
                  	                        	c_id:cid,
                  	                            data: data
                  	                        }));
                      	        		}
                      	        		timer1 = true;
                                	});
                            		task1.delay(300);
                            	}
                        	}); 
                         }
                      }	    	    		
     	    	});
        	} else {
                return;
            }
        }
    }]
});

function addCondition(record){
	var code = record.code;
	var fieldtitle = record.title;
	var flag = true;
	var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
	conditionPanel.items.each(function (item, index, length) {
        var label = item.name;
        if (code == label) {
              alert("条件已存在");
              flag = false;
              return;
          }
    });
	if(flag){
		var cid = GUID.createGUID();
		conditionList.push({
			C_ID:cid,
			C_CODE:code,
    		SHOW_CODE:code,
    		C_TITLE: fieldtitle
		});
		conditionPanel.add({
			xtype: 'combobox',
	    	fieldLabel: '<span ondblclick="deleteCondition(\''+code+'\',\'combobox\',\''+cid+'\');">'+fieldtitle+'</span>',
	    	name: code,
            margin:'2 5 2 2',
            padding:'0 0 0 0',
            listeners: {
                 render:function(self){
                 	Ext.QuickTips.init();  
                 	Ext.QuickTips.register({  
                 		target : self.el,  
                 	    text : '双击标题删除'
                 	});
                 	self.getEl().on('click', function(self){ 
                		if(timer1){
                    		timer1 = false;
                    		task1 = new Ext.util.DelayedTask(function(){
                    			var rightConfig = Ext.ComponentQuery.query('panel#rightConfig')[0];
              	        		rightConfig.removeAll(true);
              	        		rightConfig.setTitle("查询条件配置");
              	        		var data = [];
              	        		var dataFlag = false;
              	        		for(var i = 0; i < conditionList.length; i++){
              	        			var conditionCid = conditionList[i].C_ID;
              	        			if(cid == conditionCid){
              	        				data = conditionList[i];
              	        				dataFlag = true;
              	        				break;
              	        			}
              	        		}
              	        		if(dataFlag){
              	        			rightConfig.add(initConditonConfig({
          	                        	c_id:cid,
          	                            data: data
          	                        }));
              	        		}
              	        		timer1 = true;
                        	});
                    		task1.delay(300);
                    	}
                	}); 
                 }
              }	    	    		
	    	});
	} 
}
